//
//  ServiceDetailsController.swift
//  AirTravel
//
//  Created by apple on 2021/8/11.
//

import UIKit
import FWPopupView
import Moya
import SwiftyJSON



class ServiceDetailsController: UIViewController {
    
    @IBOutlet weak var tabView: UITableView!
    /// 终点站
    @IBOutlet weak var terminalLab: UILabel!
    /// 结束小时
    @IBOutlet weak var end_hoursLab: UILabel!
    /// 结束时间
    @IBOutlet weak var end_dateOfLab: UILabel!
    /// 路程时间
    @IBOutlet weak var journey_timeLab: UILabel!
    /// 车次
    @IBOutlet weak var trainsLab: UILabel!
    /// 出发站
    @IBOutlet weak var start_standingLab: UILabel!
    /// 出发小时
    @IBOutlet weak var start_hoursLab: UILabel!
    /// 出发时间
    @IBOutlet weak var start_dateOfLab: UILabel!
    
    @IBOutlet weak var screening_dateLab: UILabel!
    @IBOutlet weak var backView: UIView!
    @IBOutlet weak var timetableBtn: UIButton!
    /// 用来主动取消网络请求
    var cancelableRequest: Cancellable?
    
    var dataStr = ""
    var according = ""
    var difference = "今天"
    
    /// 出发站名称
    var fromStationName = ""
    /// 到达站名称
    var toStationName = ""
    /// 车次
    var trainNo = ""
    
    let identifyPH = "PromptHeaderView"
    let identifySIH = "SeatInformationHeaderView"
    let identifySI = "SeatInformationCell"
    var dataDic : Dictionary<String,Any>?
    var seatList : Array<Any>?
    var putOnArray = [Int]()
    /// 0选车，，1改签
    var type = 0
    
    
    lazy var radioTimeView: RadioTimeView = {
        let customPopupView = RadioTimeView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 450))
        customPopupView.delegate = self
        customPopupView.layer.cornerRadius = 5
        customPopupView.layer.masksToBounds = true
        let vProperty = FWPopupViewProperty()
        vProperty.popupCustomAlignment = .bottomCenter
        vProperty.backgroundColor = UIColor.clear
        vProperty.popupAnimationType = .frame
        vProperty.maskViewColor = UIColor(white: 0, alpha: 0.5)
        vProperty.touchWildToHide = "1"
        vProperty.popupViewEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        vProperty.animationDuration = 0.3
        customPopupView.vProperty = vProperty
    
        return customPopupView
    }()
    
    
//    lazy var trainSMSVerificationView: TrainSMSVerificationView = {
//        let customPopupView = TrainSMSVerificationView(frame: CGRect(x: 30, y: 0, width: SCREEN_WIDTH - 60, height: 240))
//        customPopupView.delegate = self
//        customPopupView.layer.cornerRadius = 5
//        customPopupView.layer.masksToBounds = true
//        let vProperty = FWPopupViewProperty()
//        vProperty.popupCustomAlignment = .center
//        vProperty.backgroundColor = UIColor.clear
//        vProperty.popupAnimationType = .frame
//        vProperty.maskViewColor = UIColor(white: 0, alpha: 0.5)
//        vProperty.touchWildToHide = "0"
//        vProperty.popupViewEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
//        vProperty.animationDuration = 0.3
//        customPopupView.vProperty = vProperty
//
//        return customPopupView
//    }()
    
    //视图将要显示
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.isNavigationBarHidden = false
        //设置导航栏背景透明
        self.navigationController?.navigationBar.setBackgroundImage(UIImage(),
                                                                    for: .default)
        self.navigationController?.navigationBar.shadowImage = UIImage()
    }
         
    //视图将要消失
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        //重置导航栏背景
        self.navigationController?.navigationBar.setBackgroundImage(nil, for: .default)
        self.navigationController?.navigationBar.shadowImage = nil
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "车次详情"
        // Do any additional setup after loading the view.
        self.timetableBtn.layer.cornerRadius = 11
        self.timetableBtn.layer.borderWidth = 1
        self.timetableBtn.layer.borderColor = UIColor.white.cgColor
        self.backView.layer.cornerRadius = 4
        self.backView.layer.masksToBounds = true
        self.screening_dateLab.text = self.according + "  \(self.difference)"
        self.tabView.layer.cornerRadius = 6
        self.tabView.layer.masksToBounds = true
        
        self.tabView.delegate = self
        self.tabView.dataSource = self
        self.tabView.tableFooterView = UIView.init()
        self.tabView.rowHeight = 60
        self.tabView.register(UINib.init(nibName: "PromptHeaderView", bundle: nil), forHeaderFooterViewReuseIdentifier: identifyPH)
        self.tabView.register(UINib.init(nibName: "SeatInformationHeaderView", bundle: nil), forHeaderFooterViewReuseIdentifier: identifySIH)
        self.tabView.register(UINib.init(nibName: "SeatInformationCell", bundle: nil), forCellReuseIdentifier: identifySI)
        
        self.searchTrainsBetweenStations()
    }
    
    //根据城市名称获取城市id接口
    func searchTrainsBetweenStations() {
        cancelableRequest = NetWorkRequest(API1.searchTrainsBetweenStations(parameters: ["departDate":self.dataStr,"fromStationName":self.fromStationName,"toStationName":self.toStationName,"trainNo":self.trainNo]), completion: {[weak self] (responseString) -> (Void) in
            let list = responseString["data"]["list"].arrayObject
            if let array = list {
                self?.dataDic = array[0] as? Dictionary<String, Any>
                if let dic = self?.dataDic {
                    self?.trainsLab.text = self?.trainNo
                    self?.terminalLab.text = "\(dic["toStationName"] ?? "")"
                    self?.end_hoursLab.text = "\(dic["arriveTime"] ?? "")"
                    self?.start_hoursLab.text = "\(dic["startTime"] ?? "")"
                    let durationMinutes = "\(dic["durationMinutes"] ?? "0")"
                    let dur = Int(durationMinutes)
                    let sfm = self?.secondsToHoursMinutesSeconds(seconds: dur ?? 0)
                    self?.journey_timeLab.text = sfm
                    self?.end_dateOfLab.text = "\(dic["arriveDate"] ?? "")"
                    self?.start_standingLab.text = "\(dic["fromStationName"] ?? "")"
                    self?.start_dateOfLab.text = "\(dic["departDate"] ?? "")"
                    self?.fromStationName = "\(dic["fromStationName"] ?? "")"
                    self?.toStationName = "\(dic["toStationName"] ?? "")"
                    self?.seatList = dic["seatList"] as? Array<Any>
                    if let array = self?.seatList {
                        for _ in array {
                            self?.putOnArray.append(0)
                        }
                    }
                }
            }
            self?.tabView.reloadData()
        }, failed: { (failedResutl) -> (Void) in
            print("服务器返回code不为0000啦~\(failedResutl)")
        }, errorResult: { () -> (Void) in
            print("网络异常")
        })
    }
    
    //获取12306登录状态接口
    func get12306LoginStatus(number:Int,type:Int) {
        let username = "\(UserDefaults.standard.value(forKey: "12306Login") ?? "")"
        if username.isEmpty {
            let vc = OfficialLoginController()
            self.navigationController?.pushViewController(vc, animated: true)
            return
        }
        if type == 1 {
            if let array = self.seatList{
                let dic = array[number] as? Dictionary<String,Any>
                //预订
                let vc = TicketReservationController()
                vc.according = self.according
                vc.dataStr = self.dataStr
                vc.difference = self.difference
                vc.trainNo = self.trainNo
                vc.fromStationName = self.fromStationName
                vc.toStationName = self.toStationName
                vc.seatDic = dic
                vc.platformType = type
                self.navigationController?.pushViewController(vc, animated: true)
            }
            return
        }
        cancelableRequest = NetWorkRequest(API1.get12306LoginStatus(parameters: ["username":username]), completion: {[weak self] (responseString) -> (Void) in
            let data = responseString["data"].dictionaryObject
            let status = "\(data?["status"] ?? "")"
            let msg = "\(data?["msg"] ?? "")"
            if status == "1" || status == "0"{//登录成功
                if let array = self?.seatList{
                    let dic = array[number] as? Dictionary<String,Any>
                    let ticketLeft = Int("\(dic?["ticketLeft"] ?? "")") ?? 0
                    if ticketLeft > 0 {
                        if self?.type == 1 {//改签
                            let vc = TrainChangeDetailsController()
                            vc.dataDic = self?.dataDic
                            vc.seatDic = dic
                            self?.navigationController?.pushViewController(vc, animated: true)
                        }else{//预订
                            let vc = TicketReservationController()
                            vc.according = self?.according ?? ""
                            vc.dataStr = self?.dataStr ?? ""
                            vc.difference = self?.difference ?? ""
                            vc.trainNo = self?.trainNo ?? ""
                            vc.fromStationName = self?.fromStationName ?? ""
                            vc.toStationName = self?.toStationName ?? ""
                            vc.seatDic = dic
                            vc.platformType = type
                            self?.navigationController?.pushViewController(vc, animated: true)
                        }
                       
                    }else{
                        YProgressHUD.showToast("暂无车票")
                    }
                }
            }else if status == "2" {//验证12306账号
                if msg == "用户名或密码错误。" {
                    let vc = OfficialLoginController()
                    self?.navigationController?.pushViewController(vc, animated: true)
                }else{
                    let vc = OfficialInformationVController()
                    self?.navigationController?.pushViewController(vc, animated: true)
                }
            }
            else{
                let vc = OfficialLoginController()
                self?.navigationController?.pushViewController(vc, animated: true)
            }
        }, failed: { (failedResutl) -> (Void) in
            print("服务器返回code不为0000啦~\(failedResutl)")
        }, errorResult: { () -> (Void) in
            print("网络异常")
        })
    }
    
    func secondsToHoursMinutesSeconds(seconds:Int) -> (String) {
        let h = seconds/60
        let m = seconds%60
        if h > 0 {
            if m > 0 {
                return "\(h)时\(m)分"
            }
            return "\(h)时"
        }else{
            if m > 0 {
                return "\(m)分"
            }
            return ""
        }
    }

    //前一天
    @IBAction func dayBefore(_ sender: UIButton) {
        self.computationTime(i: -1)
    }
    //后一天
    @IBAction func dayAfterBtn(_ sender: UIButton) {
        self.computationTime(i: 1)
    }
    //筛选日期
    @IBAction func screeningDateBtn(_ sender: UIButton) {
        self.radioTimeView.setUpData(str: self.dataStr)
        self.radioTimeView.show()
    }
    ///时刻表
    @IBAction func timetableBtn(_ sender: UIButton) {
        let vc = TimetableController()
        vc.dataStr = self.dataStr
        vc.trainNo = self.trainNo
        self.navigationController?.pushViewController(vc, animated: true)
        
    }
    
    
    func computationTime(i:Int) {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        let jtStr = dateFormatter.string(from: Date())
        guard let date1 = dateFormatter.date(from: jtStr) else { return }
        
        guard let today = dateFormatter.date(from: self.dataStr) else { return }
        let tomorrow = Calendar.current.date(byAdding: .day, value: i, to: today)
        let dataStr = dateFormatter.string(from: tomorrow!)
        dateFormatter.dateFormat = "MM月dd日"
        let according = dateFormatter.string(from: tomorrow!)
        let components = NSCalendar.current.dateComponents([.day], from: date1, to: tomorrow!)
        let components1 = NSCalendar.current.dateComponents([.weekday], from: tomorrow!)
        var difference = ""
        if components.day! < 0 {
            YProgressHUD.showToast("日期不能小于今天")
            return
        }
        if components.day == 0{
            difference = "今天"
        }else if components.day == 1 {
            difference = "明天"
        }else{
            switch components1.weekday {
            case 1:
                difference = "周日"
            case 2:
                difference = "周一"
            case 3:
                difference = "周二"
            case 4:
                difference = "周三"
            case 5:
                difference = "周四"
            case 6:
                difference = "周五"
            case 7:
                difference = "周六"
            default:
                break
            }
        }
        self.dataStr = dataStr
        self.according = according
        self.difference = difference
        self.screening_dateLab.text = self.according + "  \(self.difference)"
        self.searchTrainsBetweenStations()
    }
}

extension ServiceDetailsController:RadioTimeDelegate{
    func radioTimeClick(date: String, according: String, difference: String) {
        self.dataStr = date
        self.according = according
        self.difference = difference
        self.screening_dateLab.text = self.according + "  \(self.difference)"
        self.searchTrainsBetweenStations()
    }
    
}

extension ServiceDetailsController:UITableViewDelegate,UITableViewDataSource{
    func numberOfSections(in tableView: UITableView) -> Int{
        if let array = self.seatList {
            return array.count + 1
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return 0
        }
        let i = self.putOnArray[section - 1]
        if i == 0 {
            return 0
        }else{
            return 1
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: identifySI) as! SeatInformationCell
        cell.selectionStyle = .none
        if indexPath.row == 0 {
            cell.contentLab.text = "官网免费直购，免手续费"
            cell.titleLab.text = "12306预定"
            cell.iconImg.image = UIImage.init(named: "图层31-1")
        }else{
            cell.contentLab.text = "免登录购票，24小时服务"
            cell.titleLab.text = "航旅预定"
            cell.iconImg.image = UIImage.init(named: "图层27拷贝")
        }
        if self.type == 1 {
            cell.reservationBtn.setTitle("改签", for: .normal)
        }
        cell.reservationBtn.tag = indexPath.section
        cell.reservationBtn.number = indexPath.row
        cell.reservationBtn.addTarget(self, action: #selector(reservationSel(sender:)), for: .touchUpInside)
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat{
        return 60
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?{
        switch section {
        case 0:
            let headView = tableView.dequeueReusableHeaderFooterView(withIdentifier: identifyPH) as! PromptHeaderView
            return headView
        default:
            let headView = tableView.dequeueReusableHeaderFooterView(withIdentifier: identifySIH) as! SeatInformationHeaderView
            headView.reservationBtn.layer.cornerRadius = 6
            headView.reservationBtn.layer.masksToBounds = true
            headView.putOnBtn.layer.cornerRadius = 6
            headView.putOnBtn.layer.masksToBounds = true
            
            headView.reservationBtn.tag = section
            headView.putOnBtn.tag = section
            if self.type == 1 {
                headView.reservationBtn.setTitle("改签", for: .normal)
            }
            
            
            
            headView.putOnBtn.addTarget(self, action: #selector(putOn(sender:)), for: .touchUpInside)
            if let array = self.seatList{
                let dic = array[section - 1] as? Dictionary<String,Any>
                headView.titleLab.text = "\(dic?["seatName"] ?? "")"
                headView.priceLab.text = "￥\(dic?["maxPrice"] ?? "")"
                let ticketLeft = Int("\(dic?["ticketLeft"] ?? "")") ?? 0
                if ticketLeft > 0 {
                    
                    headView.ticketLab.text = "有票"
                    
                    headView.reservationBtn.backgroundColor = UIColor.red
                    headView.reservationBtn.addTarget(self, action: #selector(reservation(sender:)), for: .touchUpInside)
                    
//                    let gradientLayer0 = CAGradientLayer()
//                    gradientLayer0.cornerRadius = 6
//                    gradientLayer0.frame = headView.reservationBtn.bounds
//                    gradientLayer0.colors = [
//                        UIColor(red: 255.0 / 255.0, green: 142.0 / 255.0, blue: 74.0 / 255.0, alpha: 1.0).cgColor,
//                        UIColor(red: 255.0 / 255.0, green: 102.0 / 255.0, blue: 53.0 / 255.0, alpha: 1.0).cgColor]
//                    gradientLayer0.locations = [0, 1]
//                    gradientLayer0.startPoint = CGPoint(x: 0, y: 1)
//                    gradientLayer0.endPoint = CGPoint(x: 1, y: 1)
//                    headView.reservationBtn.layer.insertSublayer(gradientLayer0, at: 0)
                }else{
                    headView.ticketLab.text = "无票"
                    headView.reservationBtn.backgroundColor = UIColor.init(hexString: "C0C0C0")
                    
                    
                }
            }
            
            let i = self.putOnArray[section - 1]
            if i == 0 {
                headView.reservationBtn.isHidden = false
            }else{
                headView.reservationBtn.isHidden = true
            }
            
            
            
            return headView
        }
        
    }
    //假预定
    @objc func reservation(sender:UIButton) {
        self.putOnArray[sender.tag - 1] = 1
        self.tabView.reloadData()
    }
    //收起
    @objc func putOn(sender:UIButton) {
        self.putOnArray[sender.tag - 1] = 0
        self.tabView.reloadData()
    }
    //真预定
    @objc func reservationSel(sender:ExtensionButton) {
        self.get12306LoginStatus(number: sender.tag - 1, type: sender.number)
    }
}

extension ServiceDetailsController:TrainSMSVerificationDelegate{
    func trainSMSVerificationClick(input: String) {
        let username = "\(UserDefaults.standard.value(forKey: "12306Login") ?? "")"
        cancelableRequest = NetWorkRequest(API1.smsVerify12306Account(parameters: ["username":username,"code":input]), completion: { (responseString) -> (Void) in
            YProgressHUD.showToast("核验码成功")
        }, failed: { (failedResutl) -> (Void) in
            print("服务器返回code不为0000啦~\(failedResutl)")
        }, errorResult: { () -> (Void) in
            print("网络异常")
        })
    }
}
